<template>
  <div class="app-container">
    <!-- 数据查询区：表单 -->
    <el-form :model="queryParams" ref="queryRef" :inline="true">
      <el-form-item label="菜品名称" prop="dishName">
        <el-input
          v-model="queryParams.dishName"
          placeholder="请输入菜品名称"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="菜品分类" prop="category">
        <el-select v-model="queryParams.category" style="width: 200px" placeholder="请选择菜品分类" @keyup.enter="handleQuery">
          <!-- <el-option label="饮料" value="饮料" />
          <el-option label="主食" value="主食" />
          <el-option label="前菜" value="前菜" />
          <el-option label="甜品" value="甜品" /> -->
          <el-option v-for="item in categoryOptions" :key="item.categoryId" :label="item.categoryName" :value="item.categoryName" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery(queryRef)">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 数据操作区：按钮 -->
    <el-row :gutter="10">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Delete" @click="handleDeleteBatch" :disabled="!multiple">批量删除</el-button>
      </el-col>
    </el-row>

    <!-- 数据展示区：表格 -->
    <el-table v-loading="loading" :data="dishs" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" width="80" prop="dishId" />
      <el-table-column label="菜品名称" align="center" width="150" prop="dishName" />
      <el-table-column label="菜品价格" align="center" prop="dishPrice" />
      <el-table-column label="菜品类型" align="center" width="150" prop="dishType" />
      <el-table-column label="菜品分类" align="center" width="150" prop="category" />
      <el-table-column label="菜品图片" align="center" width="150" prop="picture" />
      <el-table-column label="状态" align="center" width="150" prop="dishStatus" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" size="small" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button link type="primary" icon="Delete" size="small" @click="handleDelete(scope.row)">删除</el-button>
          <el-button link type="primary" icon="View" size="small" @click="handleView(scope.row)">查看</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 数据展示区：分页加载 -->
    <el-pagination
      style="margin-top: 20px"
      v-model:current-page="queryParams.pageNum"
      v-model:page-size="queryParams.pageSize"
      :page-sizes="[5, 10, 20, 30]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    ></el-pagination>

    <!-- 数据编辑区：新增/修改对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="菜品名称" prop="dishName">
          <el-input v-model="form.dishName" placeholder="请输入菜品名称" />
        </el-form-item>
        <el-form-item label="菜品价格" prop="price">
          <el-input-number 
          v-model="form.dishPrice" 
          :min="0"
          :precision="2" 
          placeholder="请输入菜品价格" />
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select v-model="form.dishType" placeholder="请选择菜品类型">
            <el-option label="单品" value="单品" />
            <el-option label="套餐" value="套餐" />
          </el-select>
        </el-form-item>
        <el-form-item label="分类" prop="category">
          <el-select v-model="form.category" placeholder="请选择菜品分类">
            <!-- <el-option label="主食" value="主食" />
            <el-option label="前菜" value="前菜" />
            <el-option label="甜品" value="甜品" />
            <el-option label="饮料" value="饮料" /> -->
            <el-option v-for="item in categoryOptions" :key="item.categoryId" :label="item.categoryName"
                :value="item.categoryName" />
          </el-select>
        </el-form-item>
        <el-form-item label="口味" prop="tasteOptions">
          <!-- <el-select v-model="form.flavor" placeholder="请选择菜品口味">
            <el-option label="咸口" value="咸口" />
            <el-option label="微辣" value="微辣" />
            <el-option label="中辣" value="中辣" />
            <el-option label="特辣" value="特辣" />
          </el-select> -->
          <div class="tag-container">
      <el-tag
        v-for="(taste, index) in form.tasteOptions"
        :key="taste.tasteId"
        closable
        :type="getTasteType(taste.tasteType)"
        @close="removeTaste(index)"
      >
        {{ taste.tasteName }}({{ taste.tasteType }})
      </el-tag>
      <el-button 
        type="text" 
        icon="Plus" 
        @click="showTasteSelector"
        style="margin-left: 10px"
      >
        选择口味
      </el-button>
    </div>
        </el-form-item>

<!-- 添加口味选择对话框 -->
<el-dialog 
  title="选择口味" 
  v-model="tasteSelectorVisible" 
  width="600px"
  append-to-body
>
  <div class="taste-selector-container">
    <!-- 现有口味选择 -->
    <div class="existing-tastes">
      <h4>现有口味</h4>
      <el-table 
        :data="allTastes" 
        @selection-change="handleTasteSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="tasteName" label="口味名称" />
        <el-table-column prop="tasteType" label="类型" />
      </el-table>
    </div>
    
    <!-- 新增口味 -->
    <div class="new-taste-form">
      <h4>新增口味</h4>
      <el-form :model="newTasteForm" label-width="80px">
        <el-form-item label="类型">
          <el-select v-model="newTasteForm.tasteType">
            <el-option 
              v-for="type in tasteTypes" 
              :key="type" 
              :label="type" 
              :value="type"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="名称">
          <el-input 
            v-model="newTasteForm.tasteName" 
            placeholder="输入新口味名称"
          />
        </el-form-item>
      </el-form>
    </div>
  </div>
  
  <template #footer>
    <el-button @click="tasteSelectorVisible = false">取消</el-button>
    <el-button type="primary" @click="confirmTasteSelection">确认</el-button>
  </template>
</el-dialog>

        <el-form-item label="菜品介绍" prop="intro">
          <el-input v-model="form.intro" placeholder="请输入菜品介绍" />
        </el-form-item>
        <el-form-item label="售卖状态" prop="status">
          <el-switch 
          v-model="form.dishStatus" 
          :active-value="'下架'"
          :inactive-value="'上架'"
          active-text="下架" 
          inactive-text="上架" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm(formRef)">确 定</el-button>
          <el-button @click="resetForm(formRef)" v-show="form.dishId === undefined">重 置</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 数据查看区：抽屉 -->
    <el-drawer v-model="drawer" title="菜品信息" :with-header="false">
      <el-descriptions :title="dishTitle" :column="2" border>
        <el-descriptions-item label="菜品名称">{{ dish.dishName }}</el-descriptions-item>
        <el-descriptions-item label="菜品价格">{{ dish.dishPrice }}</el-descriptions-item>
        <el-descriptions-item label="菜品类型">{{ dish.dishType }}</el-descriptions-item>
        <el-descriptions-item label="菜品分类">{{ dish.category }}</el-descriptions-item>
        <el-descriptions-item label="菜品图片">{{ dish.picture }}</el-descriptions-item>
        <el-descriptions-item label="售卖状态">{{ dish.dishStatus }}</el-descriptions-item>
      </el-descriptions>
    </el-drawer>

    <!-- 新增口味弹窗 -->
    <el-dialog title="添加口味" v-model="tasteDialogVisible">
    <el-select 
      v-model="selectedTasteType" 
      placeholder="选择口味类型"
    >
      <el-option 
        v-for="type in tasteTypes" 
        :key="type" 
        :label="type" 
        :value="type"
      />
    </el-select>
    
    <el-input 
      v-model="newTasteName" 
      placeholder="输入口味名称" 
      style="margin-top: 10px"
    />
    
    <template #footer>
      <el-button @click="tasteDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="addNewTaste">确认</el-button>
    </template>
  </el-dialog>
  </div>
</template>

<script lang="ts" setup>
/** ------------------全局导入区-------------------- */
import { ref, reactive, toRef, onMounted } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import type{ QueryParams, DishDTO, RuleForm } from "@/views/dish/list/types";
import { listAllDish, listDish, listDishByPage, getDishById, getDishByName, getDishByCategory, addDish, updateDish, deleteDish, deleteDishBatch } from '@/api/dish';
import type { TasteDTO } from '../taste/types';
import { addTaste, listAllTaste } from '@/api/taste';
import type { CategoryDTO } from '../category/types';
import { listAllCategory } from '@/api/category';

onMounted(() => {
// 挂载后加载数据
getList()
getCategoryOptions()
})

/** ------------------数据查询区——表单-------------------- */
// 表单实例
const queryRef = ref<FormInstance>()

const categoryOptions = ref<CategoryDTO[]>([])

function getCategoryOptions(){
  listAllCategory().then(response => {
    categoryOptions.value = response.data;
  })
}

// 查询
const query = reactive<QueryParams>({
  pageNum: 1,
  pageSize: 5,
  dishName: '',
  category: '',
})
const queryParams = toRef(query)

// 数据查询区--> 查询按钮
function handleQuery() {
queryParams.value.pageNum = 1
getList()
ElMessage.success(JSON.stringify(queryParams.value))
}

// 数据查询区--> 重置按钮
const resetQuery = (formEl: FormInstance | undefined) => {
if (!formEl) return
formEl.resetFields()
getList()
}

/** ------------------数据展示区——表格-------------------- */

// 数据列表
const loading = ref<boolean>(false)  // table数据加载遮罩
const total = ref<number>(0) // table数据总数
const isEditMode = ref(false)

const dishData = reactive<DishDTO[]>([]) // table数据
const dishs = toRef(dishData)

// 响应式菜品数据
// const dishs = ref<DishDTO[]>([])

// 数据展示区--> 数据加载
const getList = async () => {
  loading.value = true
  /** 调用后端分页查询接口 */
  listDishByPage(queryParams.value).then(response => {
    dishs.value = response.data.list
    total.value = response.data.total
    loading.value = false
  })
}

/** ------------------数据展示区：数据选择-------------------- */

const ids = ref<number[]>([]) // 表单勾选的id
const single = ref<boolean>(false) // 勾选1个
const multiple = ref<boolean>(false) // 勾选多个

// 数据展示区--> 勾选数据
function handleSelectionChange(selection: DishDTO[]) {
ids.value = selection.map((item:DishDTO) => item.dishId)
single.value = selection.length == 1
multiple.value = selection.length >= 1 
}

/** ------------------数据展示区：分页加载-------------------- */
// 分页--> 修改每页数据数（5｜10｜20｜30）
function handleSizeChange(val:number) {
queryParams.value.pageSize = val
getList()
}

//分页--> 修改当前页
function handleCurrentChange(val:number) {
queryParams.value.pageNum = val
getList()
}

/** ------------------数据编辑区——对话框+表单-------------------- */
// 表单数据
const formRef = ref<FormInstance>()

const formData = reactive<RuleForm>({
  dishName: '',
  dishPrice: 0,
  dishType: '单品',
  category: '',
  picture: '',
  dishStatus: '上架',
  tasteOptions: []
})

const form  = toRef(formData)

const rules = reactive<FormRules<RuleForm>>({ // 表单验证规则
dishName: [
  { required: true, message: '菜品名称不能为空', trigger: 'blur' },
],
dishPrice: [
  { required: true, message: '菜品价格不能为空', trigger: 'blur' },
],
dishType: [
  { required: true, message: '请选择菜品类型', trigger: 'change' },
],
category: [
  { required: true, message: '请选择菜品分类', trigger: 'change' },
]
})

// 对话框数据
const title = ref('') // 对话框标题
const open = ref(false) //对话框打开

// 数据编辑区-->提交按钮
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return

await formEl.validate((valid, fields) => {
    if (valid) {
      /** 调用后端新增和修改接口 */
      if (isEditMode.value) {
        updateDish(form.value).then((response) => {
          ElMessage({type: 'success',message: '修改数据成功'})
        })
      } else {
        addDish(form.value).then((response) => {
          ElMessage({type: 'success',message: '新增数据成功'})
        })
      }
      getList()
      open.value = false
      ElMessage.success(JSON.stringify(form.value))
    } else {
      console.log('表单验证未通过', fields) // 前台会自动提示errors
    }
})
}

// 数据编辑区-->重置按钮
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}
// 数据编辑区-->取消按钮
function cancel(){
initForm()
open.value = false
}

/** ------------------数据操作区——按钮-------------------- */
// 清空或赋值表单数据
const initForm = () => {
// formRef.value?.resetFields() 
form.value = {
    dishName: '',
    dishPrice: 0,
    dishType: '单品',
    category: '',
    picture: '',
    dishStatus: '上架',
    flavor: '',
    intro: '',
    tasteOptions: []
  }
}

// 数据操作区--> 新增按钮
function handleAdd() {
  isEditMode.value = false //标记为新增模式
initForm()
title.value = '新增菜品'
open.value = true
}

// 数据操作区区--> 修改按钮
const handleUpdate = async (row: DishDTO) => {
  isEditMode.value = true
  initForm()
    const id = row.dishId || ids.value[0]

      /** 调用后端id查询接口*/
  getDishById(id).then((response) => {
    form.value = response.data
    title.value = '修改数据['+ id +']'
    open.value = true
  })
}

// 数据操作区--> 删除按钮
async function handleDelete(row: any) {
  const id = row.dishId
  ElMessageBox.confirm('是否删除编号为' + id + '的数据?','警告')
    .then(() =>{
      return deleteDish(id)
    })
    .then(() => {
        getList()
        ElMessage({type: 'success',message: '删除成功'})
    })
    .catch(() => {})    
}

// 数据操作区--> 批量删除
async function handleDeleteBatch() {
  const dishIds = ids.value
  ElMessageBox.confirm('是否批量删除编号为' + dishIds + '的数据?','警告')
    .then(() => {
      return deleteDishBatch(dishIds)
    })
    .then(() => {
        getList()
        ElMessage({type: 'success',message: '批量删除成功',})
    })
    .catch(() => {})  
}

// 数据操作区-->抽屉查看数据
const drawer = ref<boolean>(false)
const dishTitle = ref<string>('');
const dish = ref<DishDTO>({
  dishId: 1,
  dishName: '',
  dishPrice: 0.00,
  dishType: '单品',
  category: '',
  picture: '',
  dishStatus: '上架',
  tasteOptions: []
})

// 数据操作区--> 查看按钮
function handleView(row: DishDTO) {
  getDishById(row.dishId).then(response => {
    dish.value = response.data
    dishTitle.value = '查看菜品数据['+ row.dishId +']'
  })
  ElMessage.success(JSON.stringify(dish.value))
  drawer.value = true
}

// 新增响应式数据
const tasteDialogVisible = ref(false)
const selectedTasteType = ref('熟度')
const newTasteName = ref('')
const tasteTypes = ['熟度', '冰度', '甜度', '辣度', '其他']
const tasteSelectorVisible = ref(false)
const allTastes = ref<TasteDTO[]>([]) // 所有口味列表
  const selectedTastes = ref<TasteDTO[]>([]) // 已选中的口味
    const newTasteForm = reactive({
  tasteName: '',
  tasteType: '熟度'
})

// 获取所有口味
const fetchAllTastes = async () => {
  try {
    const res = await listAllTaste()
    allTastes.value = res.data
  } catch (error) {
    ElMessage.error('获取口味列表失败')
  }
}

// 显示口味选择器
const showTasteSelector = async () => {
  await fetchAllTastes()
  tasteSelectorVisible.value = true
}

// 处理口味选择变化
const handleTasteSelectionChange = (selection: TasteDTO[]) => {
  selectedTastes.value = selection
}

// 确认口味选择
const confirmTasteSelection = async () => {
  try {
    // 处理新增的口味
    if (newTasteForm.tasteName.trim()) {
      // 检查是否已存在
      const exists = allTastes.value.some(
        t => t.tasteName === newTasteForm.tasteName && 
             t.tasteType === newTasteForm.tasteType
      )
      
      if (!exists) {
        const res = await addTaste({
          tasteName: newTasteForm.tasteName,
          tasteType: newTasteForm.tasteType
        })
        selectedTastes.value.push(res.data)
      } else {
        ElMessage.warning('该口味已存在')
      }
    }
    
    // 更新菜品口味列表
    if (!form.value.tasteOptions) {
      form.value.tasteOptions = []
    }
    
    // 合并已选口味（去重）
    selectedTastes.value.forEach(taste => {
      if (!form.value.tasteOptions?.some(t => t.tasteId === taste.tasteId)) {
        form.value.tasteOptions?.push(taste)
      }
    })
    
    tasteSelectorVisible.value = false
    newTasteForm.tasteName = ''
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

const showAddTasteDialog = () => {
  // tasteDialogVisible.value = true
  // 确保tasteOptions已初始化
  if (!form.value.tasteOptions) {
    form.value.tasteOptions = []
  }
  tasteDialogVisible.value = true
  selectedTasteType.value = '熟度'
  newTasteName.value = ''
}

const addNewTaste = () => {
  // if (newTasteName.value) {
  //   form.tasteOptions.push({
  //     tasteId: Date.now(), 
  //     tasteName: newTasteName.value,
  //     tasteType: selectedTasteType.value
  //   })
  //   tasteDialogVisible.value = false
  //   newTasteName.value = ''
  // }
  if (!newTasteName.value.trim()) {
    ElMessage.warning('请输入口味名称')
    return
  }
  
  // 检查是否已存在相同名称的口味
  const exists = form.value.tasteOptions?.some(
    t => t.tasteName === newTasteName.value && t.tasteType === selectedTasteType.value
  )
  
  if (exists) {
    ElMessage.warning('该口味已存在')
    return
  }
  
  form.value.tasteOptions?.push({
    tasteId: Date.now(), // 临时ID，保存时应由后端生成
    tasteName: newTasteName.value,
    tasteType: selectedTasteType.value as any
  })
  
  tasteDialogVisible.value = false
  newTasteName.value = ''
}

const removeTaste = (index: number) => {
  form.value.tasteOptions?.splice(index, 1)
}

// 获取不同口味类型的标签样式
const getTasteType = (type: string) => {
  const map: Record<string, string> = {
    '熟度': 'warning',
    '冰度': 'info',
    '甜度': 'success',
    '辣度': 'danger',
    '其他': ''
  }
  return map[type] || ''
}

</script>